(function ($) {
    var $table = $('#table'),
        serverData = {},
        $departmentDropdown = $('#departmentDropdown'),
        tplTableBodyContent,
        rtnList = [8615214, 8615218, 8616102, 8616126, 8666898, 8667034, 8667036],
        fieldList = ['diff', 'plan', 'act', 'ok', 'scrap', 'scrapRate'],
        cellDict = {},
        inputData = {},
        tu0List = [8615214, 8615218, 8616102, 8616126],
        tu1List = [8666898, 8667034, 8667036],
        foundryDailyProduction = [
            {
                "id": "Casting",
                "Department": "Casting",
                "prozessid": "200"
            },
            {
                "id": "DMCLaser",
                "Department": "DMC Laser",
                "prozessid": "210"
            },
            {
                "id": "XRay",
                "Department": "X-Ray",
                "prozessid": "500"
            },
            {
                "id": "VI",
                "Department": "V I",
                "prozessid": "240242"
            },
            {
                "id": "HardnessCheck",
                "Department": "Hardness Check",
                "prozessid": "558"
            },
            //{
            //    "id": "ShootBlasting",
            //    "Department": "Shoot blasting",
            //    "prozessid": "270"
            //},
            {
                "id": "Grob",
                "Department": "Grob",
                "prozessid": "553"
            },
            {
                "id": "LeakTest",
                "Department": "Leak test",
                "prozessid": "570"
            },
            {
                "id": "HDS",
                "Department": "HDS",
                "prozessid": "526"
            },
            {
                "id": "CI",
                "Department": "C I",
                "prozessid": "581"
            },
            {
                "id": "LDS",
                "Department": "LDS",
                "prozessid": "528"
            },
            {
                "id": "FI",
                "Department": "F I",
                "prozessid": "601"
            }
        ],
        isTableBodyRendered = 0;

    var buildTableBodies = function () {
        var ao = {
            url: '/NEP/ALS/api/FoundryDailyProduction',
            dataType: 'JSON',
            type: 'GET',
            success: function (resp) {
                if (resp && resp['actualVolume']) {
                    serverData['actualVolume'] = resp['actualVolume'];
                    initTableData();
                }
            }
        };
        var dateFrom = $('#dateFromPicker').val(),
            dateTo = $('#dateToPicker').val();
        if (dateFrom && dateTo) {
            var data = {date_from: dateFrom, date_to: dateTo};
            ao.data = data;
        }
        $.ajax(ao);
    };

    var renderTable = function () {
        var intPtn = new RegExp('\\d+');
        $.each(cellDict, function (k, v) {
            var $elm = $('#' + k);
            if ($elm[0].localName == 'input') {
                if (intPtn.test(v['value'])) {
                    $elm.val(v['value']);
                }
                else {
                    $elm.val('');
                }
            }
            else {
                $elm.text(v['value']);
            }
        });
    };

    /**
     * 构造每个单元格里的数据字典
     * rtn 表示的是生产线的代号id，如B38A、B38B
     * @param field
     * @param processId
     * @param data
     */
    var constructCellDict = function (field, processId, data) {
        var rtnInfoList = [],
            _total = 0,
            _tu0Sum = 0,
            _tu1Sum = 0;
        $.each(rtnList, function (ii, rtn) {
            var obj = {},
                idx = processId + '_' + rtn,
                _cellId = field + '_' + idx,
                _cellValId = field + '_value';
            obj['rtn'] = rtn;
            // 允许cellDict存储的数量值为整数值及空字符
            if (data && data[idx]) {
                obj[_cellValId] = intVal(data[idx]);
            }
            else {
                if (field === 'plan' || field === 'scrap') {
                    obj[_cellValId] = '';
                }
                else {
                    obj[_cellValId] = 0;
                }
            }
            rtnInfoList.push(obj);
            if (!cellDict[_cellId]) {
                cellDict[_cellId] = {};
            }
            _total += obj[_cellValId];
            if (field == 'scrapRate') {
                obj[_cellValId] += '%';
            }
            cellDict[_cellId]['value'] = obj[_cellValId];
            if ($.inArray(rtn, tu0List) >= 0) {
                _tu0Sum += intVal(obj[_cellValId]);
            }
            if ($.inArray(rtn, tu1List) >= 0) {
                _tu1Sum += intVal(obj[_cellValId]);
            }
        });
        if (field == 'scrapRate') {
            _total += '%';
            _tu0Sum += '%';
            _tu1Sum += '%';
        }
        var _TotalId = field + '_' + processId + '_total',
            _TU0Id = field + '_' + processId + '_tu0_sum',
            _TU1Id = field + '_' + processId + '_tu1_sum';
        if (!cellDict[_TotalId]) {
            cellDict[_TotalId] = {};
            cellDict[_TU0Id] = {};
            cellDict[_TU1Id] = {};
        }
        cellDict[_TotalId]['value'] = _total;
        cellDict[_TU0Id]['value'] = _tu0Sum;
        cellDict[_TU1Id]['value'] = _tu1Sum;
    };

    var fetchInputDataFromSever = function (callback) {
        $.ajax({
            url: '/NEP/ALS/api/GetFoundryDailyProductionData',
            type: 'GET',
            dataType: 'TEXT',
            success: function (resp) {
                if (resp) {
                    var json = JSON.parse(resp);
                    $.each(json, function (idx, o) {
                        var val = Math.abs(o['value']) >= 0 ? o['value'] : '';
                        updateCellDict(idx, val);
                    })
                }
                callback.call(null);
            }
        });
    };

    var getCellDictVal = function (idx, flag) {
        var result;
        if (flag) {
            result = cellDict[idx];
        }
        else {
            result = cellDict[idx]['value'];
        }
        return result;
    };

    var setCellDictVal = function (idx, value) {
        if ($.isPlainObject(value)) {
            cellDict[idx] = value;
        }
        else {
            cellDict[idx]['value'] = value;
        }
    };

    var initTableData = function () {
        var dataDict = {
            'act': serverData['actualVolume']
        };
        var tableBodiesHtml = '';

        $.each(foundryDailyProduction, function (i, o) {
            $.each(fieldList, function (n, field) {
                constructCellDict(field, o['prozessid'], dataDict[field]);
            });
            if (isTableBodyRendered === 0) {
                tableBodiesHtml += template.render(tplTableBodyContent, o);
            }
        });
        if (isTableBodyRendered === 0) {
            isTableBodyRendered = 1;
            $table.append(tableBodiesHtml);
        }
        fetchInputDataFromSever(function () {
            renderTable();
        });
    };

    var intVal = function (val) {
        //console.log('--------------------');
        //console.log((Math.abs(val) >= 0 && parseInt(val)) ? parseInt(val) : 0);
        //console.log(val);
        return (Math.abs(val) >= 0 && parseInt(val)) ? parseInt(val) : 0;
    };

    // id: scrap_200_8615214
    var getFieldFromId = function (id) {
        var ptn = new RegExp('^([a-z]+)_.*$');
        return id.replace(ptn, '$1');
    };

    var getProcessIdFromId = function (id) {
        var ptn = new RegExp("[a-z]+_(\\d+)_\\d+");
        return id.replace(ptn, '$1');
    };

    var genIdStr = function (id, field, newField) {
        return id.replace(field, newField);
    };

    /**
     * 通过id更新cellDict的值
     * @param id
     * @param val
     * @param noNeedRender
     */
    var updateCellDict = function (id, val) {
        var numericVal = Math.abs(val) >= 0 ? parseInt(val) : 0; // 用于计算的数值
        setCellDictVal(id, val);
        var field = getFieldFromId(id);
        var processId = getProcessIdFromId(id);
        var actId = genIdStr(id, field, 'act');
        var actVal = getCellDictVal(actId),
            nActVal = intVal(actVal);

        if (field === 'scrap') {
            var okId = genIdStr(id, field, 'ok');
            var scrapRateId = genIdStr(id, field, 'scrapRate');

            var okVal = intVal(nActVal - numericVal);
            var scrapRateVal = 0;
            var scrapRateValPar;
            if (val === '') {
                okVal = 0;
            }
            else {
                if (actVal) {
                    scrapRateVal = (numericVal / nActVal);
                }
            }
            scrapRateValPar = intVal(scrapRateVal.toFixed(4) * 10000) / 100 + '%';
            setCellDictVal(okId, okVal);
            setCellDictVal(scrapRateId, scrapRateValPar);
            fieldSum(field, processId);
            fieldSum('ok', processId);
        }
        if (field === 'plan') {
            var diffId = genIdStr(id, field, 'diff');
            var diffVal = intVal(nActVal - numericVal);
            if (!val) {
                diffVal = 0;
            }
            setCellDictVal(diffId, diffVal);
            fieldSum(field, processId);
            fieldSum('diff', processId);
        }
    };

    var fieldSum = function (field, processId) {
        var _total = 0,
            _tu0Sum = 0,
            _tu1Sum = 0;
        $.each(rtnList, function (ii, rtn) {
            var idx = processId + '_' + rtn,
                _cellId = field + '_' + idx,
                _cellVal = getCellDictVal(_cellId), // 实际存储的值，可能为空字符
                _cellNumericVal = intVal(_cellVal); // 用于计算
            _total += _cellNumericVal;
            if ($.inArray(rtn, tu0List) >= 0) {
                _tu0Sum += _cellNumericVal;
            }
            if ($.inArray(rtn, tu1List) >= 0) {
                _tu1Sum += _cellNumericVal;
            }
        });

        var _TotalId = field + '_' + processId + '_total',
            _TU0Id = field + '_' + processId + '_tu0_sum',
            _TU1Id = field + '_' + processId + '_tu1_sum';
        setCellDictVal(_TotalId, _total);
        setCellDictVal(_TU0Id, _tu0Sum);
        setCellDictVal(_TU1Id, _tu1Sum);
        if (field === 'scrap') {
            var _TotalAct = 'act' + '_' + processId + '_total',
                _TU0Act = 'act' + '_' + processId + '_tu0_sum',
                _TU1Act = 'act' + '_' + processId + '_tu1_sum',
                _TotalScrapRate = 'scrapRate' + '_' + processId + '_total',
                _TU0ScrapRate = 'scrapRate' + '_' + processId + '_tu0_sum',
                _TU1ScrapRate = 'scrapRate' + '_' + processId + '_tu1_sum',
                totalActVal = getCellDictVal(_TotalAct),
                nTotalActVal = intVal(totalActVal),
                tu0ActVal = getCellDictVal(_TU0Act),
                nTu0ActVal = intVal(tu0ActVal),
                tu1ActVal = getCellDictVal(_TU1Act),
                nTu1ActVal = intVal(tu1ActVal);
            if (nTotalActVal === 0) {
                cellDict[_TotalScrapRate]['value'] = 0 + '%';
            } else {
                cellDict[_TotalScrapRate]['value'] = intVal((_total / nTotalActVal).toFixed(4) * 10000) / 100 + '%';
            }
            if (cellDict[_TU0Act]['value'] === 0) {
                cellDict[_TU0ScrapRate]['value'] = 0 + '%';
            } else {
                cellDict[_TU0ScrapRate]['value'] = intVal((_tu0Sum / nTu0ActVal).toFixed(4) * 10000) / 100 + '%';
            }
            if (cellDict[_TU1Act]['value'] === 0) {
                cellDict[_TU1ScrapRate]['value'] = 0 + '%';
            } else {
                cellDict[_TU1ScrapRate]['value'] = intVal((_tu1Sum / nTu1ActVal).toFixed(4) * 10000) / 100 + '%';
            }
        }
    };

    var getDictIndex = function (field, processId, rtn) {
        return field + '_' + processId + '_' + rtn;
    };

    // 获取手动输入的值，将这些值以字典结构返回，用于保留手动输入的数据
    var getInputData = function () {
        inputData = {};
        buildFieldGroupData('plan');
        buildFieldGroupData('scrap');
    };

    var buildFieldGroupData = function (field) {
        $.each(foundryDailyProduction, function (i, o) {
            $.each(rtnList, function (n, rtn) {
                var idx = getDictIndex(field, o['prozessid'], rtn);
                inputData[idx] = {};
                inputData[idx]['value'] = getCellDictVal(idx);
            });
        });
    };

    var saveInputDataToSever = function (data) {
        if (!(data && data['data'])) {
            data = {
                data: ''
            };
        }
        $.ajax({
            url: '/NEP/ALS/api/SetFoundryDailyProductionData',
            data: data,
            type: 'POST',
            dataType: 'JSON',
            success: function (resp) {
                console.log(resp);
            }
        });
    };

    var navTo = function (hrefId, fixTop) {
        $('html,body').animate({
            scrollTop: intVal($(hrefId).offset().top + fixTop)
        }, 300);
    };

    var buildDropdownList = function () {
        var ddHtml = '';
        $.each(foundryDailyProduction, function (i, o) {
            ddHtml += '<div class="item" data-value="' + o.id + '">' + o.Department + '</div>';
        });
        $departmentDropdown.find('.menu').html(ddHtml);
        $departmentDropdown.dropdown({
            onChange: function (value, text, $selectedItem) {
                navTo('#tb' + value, -70);
            }
        });
    };

    var initDatePicker = function () {
        var YYYY = moment().format('YYYY');
        new Pikaday({
            format: 'DD.MM.YYYY',
            field: document.getElementById('dateFromPicker'),
            trigger: document.getElementById('dateFromPickerButton'),
            minDate: new Date(2003, 0, 1),
            maxDate: moment().toDate(),
            yearRange: [2003, YYYY]
        });
        new Pikaday({
            format: 'DD.MM.YYYY',
            field: document.getElementById('dateToPicker'),
            trigger: document.getElementById('dateToPickerButton'),
            minDate: new Date(2003, 0, 1),
            maxDate: moment().toDate(),
            yearRange: [2003, YYYY]
        });

        var yesterdayDate = moment().add(-1, 'd').format('DD.MM.YYYY');
        var todayDate = moment().format('DD.MM.YYYY');
        $('#dateFromPicker').val(yesterdayDate);
        $('#dateToPicker').val(todayDate);
    };

    $(function () {
        $.get('/static/data/FoundryDailyProduction', function (text) {
            if (text) {
                tplTableBodyContent = text;
                buildTableBodies();
            }
        });
        $('#table').on('keyup', 'input', function (evt) {
            var $this = $(this);
            var id = $this.attr('id');
            var val = $this.val();
            if (!val) {
                val = '';
            }
            updateCellDict(id, val);
            renderTable();
        }).on('focus', 'input', function (evt) {
            var $this = $(this);
            $this.removeClass('app-input-blur');
        }).on('blur', 'input', function (evt) {
            var $this = $(this);
            $this.addClass('app-input-blur');
        });


        $('.__JSave').on('click', function () {
            getInputData();
            var data = {
                data: JSON.stringify(inputData)
            };
            saveInputDataToSever(data);
        });

        $('.__JClean').on('click', function () {
            saveInputDataToSever('');
            //$('#dailyProduction')[0].reset();
            initTableData();
        });

        buildDropdownList();

        $('.ui.sticky').sticky({
            context: 'body'
        });

        initDatePicker();

        $('#filterButton').on('click', function () {
            //$table.find('tbody').remove();
            buildTableBodies();
        });
    });


})(jQuery);